<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="0" class="add">
      <el-col :span="12">
        <el-input v-model="page.query" placeholder="请输入内容" clearable v-on:clear="slect()"></el-input>
        <!--clera是个事件-->
      </el-col>
      <el-col :span="5">
        <el-button icon="el-icon-search" type="primary" @click="slect"></el-button>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" :span="6" @click="dialogVisible = true">添加用户</el-button>
      </el-col>
    </el-row>
    <!--用户管理区-->
    <div class="contene">
      <template>
        <el-table :data="tableData" border style="width: 100%" stripe>
          <!--页数区-->
          <el-table-column type="index" label="#"></el-table-column>
          <!--用户-->
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <!--邮箱-->
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <!--联系-->
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <!--用户-->
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <!--状态-->
          <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                v-on:change="state(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <!--操作-->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="small"
                v-on:click="handleEdit(scope.row.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                v-on:click="handleDelete(scope.row.id)"
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button type="warning" icon="el-icon-star-off" size="small" @click="selerole(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>
    <!--分页操作-->
    <div class="buttom">
      <template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChang"
            @current-change="handleCurrentChange"
            :current-page="page.pagenum"
            :page-sizes="[2, 4, 6, 8]"
            :page-size="page.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="Index"
          ></el-pagination>
        </div>
      </template>
    </div>
    <!--添加用户的列表-->
    <div>
      <el-dialog
        title="新用户的添加"
        :visible.sync="dialogVisible"
        width="50%"
        v-on:close="isinit('bindRefl')"
      >
        <el-form
          :model="Reflow"
          :rules="verify"
          ref="bindRefl"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item prop="username" label="用户名">
            <el-input v-model="Reflow.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="Reflow.password"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="Reflow.email"></el-input>
          </el-form-item>
          <el-form-item prop="mobile" label="手机">
            <el-input v-model.number="Reflow.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="Add()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!--用户修改页面-->
    <div>
      <el-dialog title="提示" :visible.sync="UpdateVisible" width="50%">
        <el-form
          :model="Update"
          status-icon
          :rules="updaterules"
          ref="ruleDate"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="Update.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="Update.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="Update.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="UpdateVisible = false">取 消</el-button>
          <el-button type="primary" @click="UpdateInfo">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!--删除用户页面-->
    <div></div>
    <!--角色分配-->
    <el-dialog title="分配角色" :visible.sync="roleVisible" width="50%" @close="initrole()">
      <div class="contene">当前的用户 : {{authrole.username}}</div>
      <div class="contene">当前的角色 : {{authrole.role_name}}</div>
      <div class="contene">
        分配的新角色 : 
        <el-select v-model="Newrole" placeholder="请选择">
          <el-option
            v-for="item in rouelArr"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"      
          ></el-option>   <!--:value=item.id 是传递给model的值-->
        </el-select>
      </div>
      <!---->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="uprole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "user",
  created: function() {
    this.getUserDate(); //请求数据
  },
  data: function() {
    /*邮箱验证*/
    var isEmail = function(ref, val, cb) {
      const isemail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (isemail.test(val)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱地址"));
    };
    /*手机验证*/
    var isIpione = function(ref, val, cb) {
      const iphone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      let a = val.toString();
      if (iphone.test(a)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号码"));
    };
    return {
      //控制显示数据
      page: {
        query: "", //搜索值
        pagenum: 1, //当前页
        pagesize: 2 //显示几条数据
      },
      Index: 0, //总条数
      tableData: [], //显示数据的条数
      //用户添加的数据
      dialogVisible: false, //用户添加提示框
      //添加用户表单
      Reflow: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //用户数据验证器
      verify: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "请输入3~8位数的规则" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 12, message: "请输入6~12位数的规则" }
        ],
        email: [
          { required: true, message: "请输入邮箱" },
          {
            validator: isEmail,
            trigger: "blur",
            type: "email"
          } /**validator:自定义验证规则 */
        ],
        mobile: [
          { required: true, message: "输入手机号码", trigger: "blur" },
          { validator: isIpione, type: "number", trigger: "blur" }
        ]
      },
      UpdateVisible: false, //用户修改提示框
      Update: {}, //用户修改的数据对象
      //用户修改的校验规则
      updaterules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱" },
          {
            trigger: "blur",
            validator: isEmail,
            message: "请输入正确的邮箱地址"
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号码" },
          {
            validator: isIpione,
            trigger: "blur",
            message: "请输入正确的手机号码"
          }
        ]
      },
      //分配角色框
      roleVisible: false,
      //当前的角色
      authrole:{
        role_name:'',
        username:''
      },
      //新角色选中值
      Newrole: "",
      //角色列表
      rouelArr:[]
    };
  },
  methods: {
    //初始化函数
    getUserDate: async function() {
      let that = this;
      let { data: res } = await this.$http.get("users", {
        params: that.page
      });
      if (res.meta.status != 200) {
        this.$message.error("请求失败");
      }
      //console.log(res);
      //总数据索引值
      this.Index = res.data.total;
      //更新页面数据（数组）
      this.tableData = res.data.users;
      //console.log(this.tableData);
    },
    /*添加用户*/
    Add: function() {
      let that = this;
      this.$refs.bindRefl.validate(async valid => {
        if (valid) {
          let { data: res } = await this.$http.post("users", this.Reflow);
          if (res.meta.status != "201") {
            this.$message.error("该用户已经存在");
            return false;
          }
          this.$message.success(res.meta.msg);
          that.dialogVisible = false;
          //重新获取用户列表
          this.getUserDate();
        } else {
          that.$message.error("请输入必填数据");
          return false;
        }
      });
    },
    /*重置表单项 */
    isinit: function(dom) {
      this.$refs[dom].resetFields();
    },
    /*搜索用户*/
    slect: function() {
      this.getUserDate();
    },
    /*用户状态*/
    state: async function(val) {
      let { data: res } = await this.$http.put(
        `users/${val.id}/state/${val.mg_state}`
      );
      if (res.meta.status != 200) {
        this.$message.error("修改状态失败");
        val.mg_state = !val.mg_state;
      }
      this.$message.success("状态更新成功");
      this.getUserDate();
    },
    /*用户删除*/
    handleDelete: async function(id) {
      let tr = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "删除用户资料",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(item => item);
      console.log(tr);
      //获得当前的用户的id
      //如果用户点击了确认
      //发送ajax请求
      //提示删除成功，从定向
      if (tr == "confirm") {
        let { data: res } = await this.$http.delete("users/" + id, { id: id });
        if (res.meta.status != 200) {
          this.$message.error("删除失败");
          return false;
        }
        this.$message.success("用户删除成功");
        this.getUserDate();
      } else if (tr == "cancel") {
        this.$message("取消删除");
      }
    },
    /*用户更新编辑*/
    handleEdit: async function(id) {
      /*
       */
      //弹出对话框
      this.UpdateVisible = true;
      //发送ajax获取数据
      let { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status != 200) {
        this.$message.error("获取用户信息失败");
        return;
      }
      //附加数据
      this.Update = res.data;
    },
    /*用户更新编辑成功响应*/
    UpdateInfo: function() {
      this.$refs.ruleDate.validate(async valid => {
        if (!valid) {
          this.$message.error("更新失败");
          return false;
        }
        //发送ajax请求
        let { data: res } = await this.$http.put("users/" + this.Update.id, {
          email: this.Update.email,
          mobile: this.Update.mobile
        });
        if (res.meta.status != "200") {
          this.$message.error(res.meta.msg);
          return false;
        }
        //成功提示成功
        this.$message.success("修改用户成功");
        //关闭对话框
        this.UpdateVisible = false;
        //清空数据，刷新数据
        this.getUserDate();
      });
      //
    },
    /*当前显示的数据*/
    handleSizeChang: function(val) {
      this.page.pagesize = val;
      this.getUserDate();
    },
    /*当前页数*/
    handleCurrentChange: function(val) {
      this.page.pagenum = val;
      this.getUserDate();
    },
    /*渲染当前角色页面*/
    async selerole(id) {
     // console.log(id);   
      let {data:res} = await this.$http.get('roles');
      if(res.meta.status!=200){
        return this.$message.error('获取角色失败');
      }
      //该用户原本的信息
      this.authrole = id;
       //渲染数据
      this.rouelArr = res.data;
       //弹出对话框
      this.roleVisible = true;
    },
    /**分配用户角色*/
    async uprole(){
      if(!this.Newrole){
        return this.$message.error('请选择角色');
      }
      let {data:res} = await this.$http.put(`users/${this.authrole.id}/role`,{rid:this.Newrole});
      if(res.meta.status!=200){
        console.log(res.meta);
        return this.$message.error('修改角色失败');
      }
      //console.log(res);
      //关闭弹框
      this.roleVisible = false;
      this.$message.success('修改角色成功');
      this.getUserDate();
    },
    //清空选中的角色
    initrole(){
      this.Newrole='';
    }
  }
};
</script>

<style scoped lang="less">
.add {
  margin-top: 20px;
}
.contene {
  margin-top: 15px;
}
.buttom {
  margin-top: 15px;
}
</style>
